﻿using System;
using System.Collections.Generic;
using System.Configuration;
using SubSonic.Repository;

namespace UMS.Data
{
    /// <summary>
    /// Simple data access instances using the SubSonic SimpleRepository.
    /// </summary>
    public static class Repository
    {
        private static readonly Dictionary<string, SimpleRepository> _simpleRepositoryInstances = new Dictionary<string, SimpleRepository>();

        /// <summary>
        /// Gets the default simple repository instance using the
        /// connection string "Platform.Data.Repository.ConnectionString".
        /// </summary>
        /// <returns>The default SimpleRepository instance.</returns>
        public static SimpleRepository Default()
        {
            return ByName("UMSConnectionString");
        }

        /// <summary>
        /// Gets the simple repository instance initialised by the specified
        /// connection string.
        /// </summary>
        /// <param name="connectionStringName">The name of the connection string to use to initialise the connection.</param>
        /// <returns>The specified SimpleRepository instance.</returns>
        public static SimpleRepository ByName(string connectionStringName)
        {
            if (!_simpleRepositoryInstances.ContainsKey(connectionStringName))
            {
                if (ConfigurationManager.ConnectionStrings[connectionStringName] == null)
                    throw new Exception("The connection string \"" + connectionStringName + "\" must be specified for this application to function correctly.");
                _simpleRepositoryInstances.Add(connectionStringName, new SimpleRepository(connectionStringName));
            }
            return _simpleRepositoryInstances[connectionStringName];
        }
    }
}
